package com.bdqn.qnnews.rest.handler;

import cn.hutool.core.bean.BeanUtil;
import com.bdqn.qnnews.common.base.R;
import com.bdqn.qnnews.common.base.ResultCode;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 自定义的全局404异常处理器
 * @author xlzhang
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
// 让当前自定义的404异常处理器在系统默认的 ErrorMvcAutoConfiguration 配置类前面执行
@AutoConfigureBefore(ErrorMvcAutoConfiguration.class)
public class Global404ExceptionHandler extends BasicErrorController {

	public Global404ExceptionHandler(ServerProperties serverProperties) {
		super(new DefaultErrorAttributes(), serverProperties.getError());
	}

	/**
	 * 覆盖默认的JSON响应方法，定义自己的响应数据格式
	 */
	@Override
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
		HttpStatus status = getStatus(request);
		// 获取异常消息集合
		Map<String, Object> originalMsgMap = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
		// 封装数据为统一响应格式
		final R<Map<String, Object>> errorR = R.error(ResultCode.NO_HANDLER_FOUND,originalMsgMap);
		// 将R对象转换为map集合
        final Map<String, Object> errorMap = BeanUtil.beanToMap(errorR);

		return new ResponseEntity<>(errorMap, status);
	}
}